const db = require('../config/db');

class Post {
    // 创建新帖子
    static async create(postData) {
        try {
            const {
                title,
                content,
                post_type,
                category,
                user_id,
                image_urls,
                video_url,
                tags
            } = postData;

            // 生成帖子ID
            const post_id = Date.now().toString() + Math.random().toString(36).substr(2, 9);

            // 插入新帖子
            const [result] = await db.execute(
                `INSERT INTO t_post (
                    post_id, title, content, post_type, category, user_id,
                    image_urls, video_url, tags
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [
                    post_id,
                    title,
                    content,
                    post_type,
                    category,
                    user_id,
                    image_urls ? JSON.stringify(image_urls) : null,
                    video_url,
                    tags
                ]
            );

            return post_id;
        } catch (error) {
            throw error;
        }
    }

    // 获取帖子列表（支持分页和筛选）
    static async getPosts(options = {}) {
        try {
            const {
                page = 1,
                limit = 10,
                sort = 'create_time',
                order = 'DESC',
                post_type,
                category,
                search
            } = options;

            let whereClause = 'WHERE 1=1';
            let params = [];

            // 添加筛选条件
            if (post_type && post_type !== 'all') {
                whereClause += ' AND post_type = ?';
                params.push(post_type);
            }

            if (category && category !== 'all') {
                whereClause += ' AND category = ?';
                params.push(category);
            }

            if (search) {
                whereClause += ' AND (title LIKE ? OR content LIKE ?)';
                params.push(`%${search}%`, `%${search}%`);
            }

            // 确保参数类型正确
            const pageNum = parseInt(page) || 1;
            const limitNum = parseInt(limit) || 10;
            const offset = (pageNum - 1) * limitNum;

            // 构建排序条件
            let orderClause = 'ORDER BY ';
            switch (sort) {
                case 'hot':
                    orderClause += 'like_count DESC, view_count DESC';
                    break;
                case 'comments':
                    orderClause += 'comment_count DESC';
                    break;
                case 'likes':
                    orderClause += 'like_count DESC';
                    break;
                default:
                    orderClause += 'create_time DESC';
            }

            // 构建完整的SQL查询
            const sql = `SELECT 
                p.*,
                u.nickname as author_name,
                u.avatar as author_avatar
            FROM t_post p
            LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
            ${whereClause}
            ${orderClause}
            LIMIT ? OFFSET ?`;

            // 构建参数数组
            const queryParams = [...params, limitNum, offset];

            console.log('SQL查询:', sql);
            console.log('参数:', queryParams);
            console.log('参数数量:', queryParams.length);

            // 查询帖子列表
            const [posts] = await db.query(sql, queryParams);

            // 查询总数 - 修复计数查询，使其与主查询保持一致
            const countSql = `SELECT COUNT(*) as total 
                FROM t_post p
                LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
                ${whereClause}`;
            const [countResult] = await db.query(countSql, params);

            return {
                posts,
                total: countResult[0].total,
                page: pageNum,
                limit: limitNum,
                totalPages: Math.ceil(countResult[0].total / limitNum)
            };
        } catch (error) {
            console.error('getPosts方法错误:', error);
            throw error;
        }
    }

    // 获取用户帖子列表
    static async getUserPosts(options = {}) {
        try {
            const {
                page = 1,
                limit = 10,
                sort = 'create_time',
                order = 'DESC',
                user_id
            } = options;

            if (!user_id) {
                throw new Error('用户ID不能为空');
            }

            let whereClause = 'WHERE p.user_id = ?';
            let params = [user_id];

            // 确保参数类型正确
            const pageNum = parseInt(page) || 1;
            const limitNum = parseInt(limit) || 10;
            const offset = (pageNum - 1) * limitNum;

            // 构建排序条件
            let orderClause = 'ORDER BY ';
            switch (sort) {
                case 'hot':
                    orderClause += 'like_count DESC, view_count DESC';
                    break;
                case 'comments':
                    orderClause += 'comment_count DESC';
                    break;
                case 'likes':
                    orderClause += 'like_count DESC';
                    break;
                default:
                    orderClause += 'create_time DESC';
            }

            // 构建完整的SQL查询
            const sql = `SELECT 
                p.*,
                u.nickname as author_name,
                u.avatar as author_avatar
            FROM t_post p
            LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
            ${whereClause}
            ${orderClause}
            LIMIT ? OFFSET ?`;

            // 构建参数数组
            const queryParams = [...params, limitNum, offset];

            console.log('用户帖子SQL查询:', sql);
            console.log('参数:', queryParams);

            // 查询用户帖子列表
            const [posts] = await db.query(sql, queryParams);

            // 查询总数
            const countSql = `SELECT COUNT(*) as total 
                FROM t_post p
                LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
                ${whereClause}`;
            const [countResult] = await db.query(countSql, params);

            return {
                posts,
                total: countResult[0].total,
                page: pageNum,
                limit: limitNum,
                totalPages: Math.ceil(countResult[0].total / limitNum)
            };
        } catch (error) {
            console.error('getUserPosts方法错误:', error);
            throw error;
        }
    }

    // 搜索帖子（支持标题和内容搜索）
    static async searchPosts(options = {}) {
        try {
            const {
                page = 1,
                limit = 10,
                sort = 'create_time',
                order = 'DESC',
                post_type,
                category,
                search,
                search_title = true,
                search_content = true
            } = options;

            let whereClause = 'WHERE 1=1';
            let params = [];

            // 添加筛选条件
            if (post_type && post_type !== 'all') {
                whereClause += ' AND post_type = ?';
                params.push(post_type);
            }

            if (category && category !== 'all') {
                whereClause += ' AND category = ?';
                params.push(category);
            }

            // 构建搜索条件
            if (search && search.trim()) {
                const searchConditions = [];
                
                if (search_title) {
                    searchConditions.push('title LIKE ?');
                    params.push(`%${search.trim()}%`);
                }
                
                if (search_content) {
                    searchConditions.push('content LIKE ?');
                    params.push(`%${search.trim()}%`);
                }
                
                if (searchConditions.length > 0) {
                    whereClause += ` AND (${searchConditions.join(' OR ')})`;
                }
            }

            // 确保参数类型正确
            const pageNum = parseInt(page) || 1;
            const limitNum = parseInt(limit) || 10;
            const offset = (pageNum - 1) * limitNum;

            // 构建排序条件
            let orderClause = 'ORDER BY ';
            switch (sort) {
                case 'hot':
                    orderClause += 'like_count DESC, view_count DESC';
                    break;
                case 'comments':
                    orderClause += 'comment_count DESC';
                    break;
                case 'likes':
                    orderClause += 'like_count DESC';
                    break;
                default:
                    orderClause += 'create_time DESC';
            }

            // 构建完整的SQL查询
            const sql = `SELECT 
                p.*,
                u.nickname as author_name,
                u.avatar as author_avatar
            FROM t_post p
            LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
            ${whereClause}
            ${orderClause}
            LIMIT ? OFFSET ?`;

            // 构建参数数组
            const queryParams = [...params, limitNum, offset];

            console.log('搜索SQL查询:', sql);
            console.log('搜索参数:', queryParams);

            // 查询帖子列表
            const [posts] = await db.query(sql, queryParams);

            // 查询总数 - 修复计数查询，使其与主查询保持一致
            const countSql = `SELECT COUNT(*) as total 
                FROM t_post p
                LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
                ${whereClause}`;
            const [countResult] = await db.query(countSql, params);

            return {
                posts,
                total: countResult[0].total,
                page: pageNum,
                limit: limitNum,
                totalPages: Math.ceil(countResult[0].total / limitNum)
            };
        } catch (error) {
            console.error('searchPosts方法错误:', error);
            throw error;
        }
    }

    // 获取单个帖子详情
    static async getPostById(postId) {
        try {
            const [posts] = await db.execute(
                `SELECT 
                    p.*,
                    u.nickname as author_name,
                    u.avatar as author_avatar,
                    u.level as author_level
                FROM t_post p
                LEFT JOIN t_user u ON p.user_id COLLATE utf8mb4_unicode_ci = u.user_id COLLATE utf8mb4_unicode_ci
                WHERE p.post_id = ?`,
                [postId]
            );

            if (posts.length === 0) {
                return null;
            }

            const post = posts[0];
            
            // 解析图片URL列表
            if (post.image_urls) {
                try {
                    post.image_urls = JSON.parse(post.image_urls);
                } catch (e) {
                    post.image_urls = [];
                }
            } else {
                post.image_urls = [];
            }

            return post;
        } catch (error) {
            throw error;
        }
    }

    // 增加浏览量
    static async incrementViewCount(postId) {
        try {
            await db.execute(
                'UPDATE t_post SET view_count = view_count + 1 WHERE post_id = ?',
                [postId]
            );
        } catch (error) {
            throw error;
        }
    }

    // 点赞/取消点赞
    static async toggleLike(postId, userId) {
        try {
            console.log('开始点赞操作 - 帖子ID:', postId, '用户ID:', userId);
            
            // 简单实现：每次点击都增加点赞数
            await db.execute(
                'UPDATE t_post SET like_count = like_count + 1 WHERE post_id = ?',
                [postId]
            );
            
            console.log('数据库更新完成');
            
            // 获取更新后的点赞数
            const likeCount = await Post.getLikeCount(postId);
            console.log('获取到的新点赞数:', likeCount);
            
            const result = { action: 'like', liked: true, likeCount };
            console.log('返回结果:', result);
            
            return result;
        } catch (error) {
            console.error('点赞操作失败:', error);
            throw error;
        }
    }

    // 获取帖子的点赞数
    static async getLikeCount(postId) {
        try {
            const [result] = await db.execute(
                'SELECT like_count FROM t_post WHERE post_id = ?',
                [postId]
            );
            
            return result.length > 0 ? result[0].like_count : 0;
        } catch (error) {
            throw error;
        }
    }

    // 删除帖子
    static async deletePost(postId, userId) {
        try {
            const [result] = await db.execute(
                'DELETE FROM t_post WHERE post_id = ? AND user_id = ?',
                [postId, userId]
            );
            
            return result.affectedRows > 0;
        } catch (error) {
            throw error;
        }
    }

    // 更新帖子
    static async updatePost(postId, userId, updateData) {
        try {
            const {
                title,
                content,
                post_type,
                category,
                image_urls,
                video_url,
                tags
            } = updateData;

            const [result] = await db.execute(
                `UPDATE t_post SET 
                    title = ?, content = ?, post_type = ?, category = ?,
                    image_urls = ?, video_url = ?, tags = ?
                WHERE post_id = ? AND user_id = ?`,
                [
                    title,
                    content,
                    post_type,
                    category,
                    image_urls ? JSON.stringify(image_urls) : null,
                    video_url,
                    tags,
                    postId,
                    userId
                ]
            );

            return result.affectedRows > 0;
        } catch (error) {
            throw error;
        }
    }
}

module.exports = Post; 